/*
 * PiView.java
 *
 * Created on October 30, 2008, 12:41 PM
 */

package researchgrants.parts.pi;

import researchgrants.parts.pi.departments.LoggedDataPanelsListDepartment;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import researchgrants.parts.GrantRequest.AllGrantRequests;
import researchgrants.parts.GrantRequest.GrantRequestsList;
import researchgrants.parts.GrantRequest.filters.GrantRequestsListFilters;
import researchgrants.parts.LoggedData.LoggedData;
import researchgrants.parts.LoggedData.panels.LoggedDataPanelsText;
import researchgrants.parts.LoggedData.panels.LoggedDataPanelsTextArea;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import researchgrants.parts.db.Db;
import researchgrants.parts.panelsManager.LoggedDataPanelsManager;
import researchgrants.utils.MyDialog;

/**
 *
 * @author  DOStudent1
 */
public class PiView extends MyDialog {

    final static int hgap=0;
    
    Pi pi;
    
    boolean isNewPi;
    
    /** Creates new form GrantRequestView */
    // Creates an unbounded grant request view - for creating a new grant request
    public PiView(Window parent) {
        super(parent);
        isNewPi=true;
        initComponents();
        initDisplay();
    }
    
    // Creates a bounded grant request view - for viewing or editing a grant request
    public PiView(Window parent, Pi pi) {
        super(parent);
        this.pi=pi;
        isNewPi=false;
        initComponents();
        initDisplay();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        pnlID = new javax.swing.JPanel();
        lblCaptionId = new javax.swing.JLabel();
        lblId = new javax.swing.JLabel();
        pnlName = new javax.swing.JPanel();
        lblCaptionName = new javax.swing.JLabel();
        pnlFieldName = new javax.swing.JPanel();
        pnlPhone = new javax.swing.JPanel();
        lblCaptionPhone = new javax.swing.JLabel();
        pnlFieldPhone = new javax.swing.JPanel();
        pnlEmail = new javax.swing.JPanel();
        lblCaptionEmail = new javax.swing.JLabel();
        pnlFieldEmail = new javax.swing.JPanel();
        pnlDepartment = new javax.swing.JPanel();
        pnlDepartment2 = new javax.swing.JPanel();
        lblCaptionDepartment = new javax.swing.JLabel();
        pnlFieldDepartment = new javax.swing.JPanel();
        pnlNotes = new javax.swing.JPanel();
        pnlNotes2 = new javax.swing.JPanel();
        lblCaptionNotes = new javax.swing.JLabel();
        pnlFieldNotes = new javax.swing.JPanel();
        pnlActionButtons = new javax.swing.JPanel();
        pnlOptionalButtons = new javax.swing.JPanel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(researchgrants.ResearchGrantsApp.class).getContext().getResourceMap(PiView.class);
        setTitle(resourceMap.getString("Form.title")); // NOI18N
        setName("Form"); // NOI18N
        getContentPane().setLayout(new javax.swing.BoxLayout(getContentPane(), javax.swing.BoxLayout.PAGE_AXIS));

        pnlID.setName("pnlID"); // NOI18N
        pnlID.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, hgap, 0));

        lblCaptionId.setText(resourceMap.getString("lblCaptionId.text")); // NOI18N
        lblCaptionId.setName("lblCaptionId"); // NOI18N
        pnlID.add(lblCaptionId);

        lblId.setText(resourceMap.getString("lblId.text")); // NOI18N
        lblId.setName("lblId"); // NOI18N
        pnlID.add(lblId);

        getContentPane().add(pnlID);

        pnlName.setName("pnlName"); // NOI18N
        pnlName.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, hgap, 0));

        lblCaptionName.setText(resourceMap.getString("lblCaptionName.text")); // NOI18N
        lblCaptionName.setName("lblCaptionName"); // NOI18N
        pnlName.add(lblCaptionName);

        pnlFieldName.setName("pnlFieldName"); // NOI18N
        pnlFieldName.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 0, 0));
        pnlName.add(pnlFieldName);

        getContentPane().add(pnlName);

        pnlPhone.setName("pnlPhone"); // NOI18N
        pnlPhone.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, hgap, 0));

        lblCaptionPhone.setText(resourceMap.getString("lblCaptionPhone.text")); // NOI18N
        lblCaptionPhone.setVerticalAlignment(javax.swing.SwingConstants.TOP);
        lblCaptionPhone.setName("lblCaptionPhone"); // NOI18N
        lblCaptionPhone.setVerticalTextPosition(javax.swing.SwingConstants.TOP);
        pnlPhone.add(lblCaptionPhone);

        pnlFieldPhone.setName("pnlFieldPhone"); // NOI18N
        pnlFieldPhone.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 0, 0));
        pnlPhone.add(pnlFieldPhone);

        getContentPane().add(pnlPhone);

        pnlEmail.setName("pnlEmail"); // NOI18N
        pnlEmail.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, hgap, 0));

        lblCaptionEmail.setText(resourceMap.getString("lblCaptionEmail.text")); // NOI18N
        lblCaptionEmail.setVerticalAlignment(javax.swing.SwingConstants.TOP);
        lblCaptionEmail.setName("lblCaptionEmail"); // NOI18N
        lblCaptionEmail.setVerticalTextPosition(javax.swing.SwingConstants.TOP);
        pnlEmail.add(lblCaptionEmail);

        pnlFieldEmail.setName("pnlFieldEmail"); // NOI18N
        pnlFieldEmail.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 0, 0));
        pnlEmail.add(pnlFieldEmail);

        getContentPane().add(pnlEmail);

        pnlDepartment.setName("pnlDepartment"); // NOI18N
        pnlDepartment.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, hgap, 0));

        pnlDepartment2.setName("pnlDepartment2"); // NOI18N
        pnlDepartment2.setLayout(new java.awt.GridBagLayout());

        lblCaptionDepartment.setText(resourceMap.getString("lblCaptionDepartment.text")); // NOI18N
        lblCaptionDepartment.setVerticalAlignment(javax.swing.SwingConstants.TOP);
        lblCaptionDepartment.setName("lblCaptionDepartment"); // NOI18N
        lblCaptionDepartment.setVerticalTextPosition(javax.swing.SwingConstants.TOP);
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        pnlDepartment2.add(lblCaptionDepartment, gridBagConstraints);

        pnlFieldDepartment.setName("pnlFieldDepartment"); // NOI18N
        pnlFieldDepartment.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 0, 0));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH;
        pnlDepartment2.add(pnlFieldDepartment, gridBagConstraints);

        pnlDepartment.add(pnlDepartment2);

        getContentPane().add(pnlDepartment);

        pnlNotes.setName("pnlNotes"); // NOI18N
        pnlNotes.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, hgap
            , 0));

    pnlNotes2.setName("pnlNotes2"); // NOI18N
    pnlNotes2.setLayout(new java.awt.GridBagLayout());

    lblCaptionNotes.setText(resourceMap.getString("lblCaptionNotes.text")); // NOI18N
    lblCaptionNotes.setVerticalAlignment(javax.swing.SwingConstants.TOP);
    lblCaptionNotes.setAlignmentY(1.0F);
    lblCaptionNotes.setName("lblCaptionNotes"); // NOI18N
    lblCaptionNotes.setVerticalTextPosition(javax.swing.SwingConstants.TOP);
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridwidth = java.awt.GridBagConstraints.RELATIVE;
    gridBagConstraints.gridheight = java.awt.GridBagConstraints.RELATIVE;
    gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHEAST;
    pnlNotes2.add(lblCaptionNotes, gridBagConstraints);

    pnlFieldNotes.setName("pnlFieldNotes"); // NOI18N
    pnlFieldNotes.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 0, 0));
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER;
    gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH;
    pnlNotes2.add(pnlFieldNotes, gridBagConstraints);

    pnlNotes.add(pnlNotes2);

    getContentPane().add(pnlNotes);

    pnlActionButtons.setName("pnlActionButtons"); // NOI18N
    pnlActionButtons.setLayout(new javax.swing.BoxLayout(pnlActionButtons, javax.swing.BoxLayout.LINE_AXIS));
    getContentPane().add(pnlActionButtons);

    pnlOptionalButtons.setName("pnlOptionalButtons"); // NOI18N
    pnlOptionalButtons.setLayout(new javax.swing.BoxLayout(pnlOptionalButtons, javax.swing.BoxLayout.LINE_AXIS));
    getContentPane().add(pnlOptionalButtons);

    pack();
    }// </editor-fold>//GEN-END:initComponents

    /////////////////////////////
    // all the internal values
    /////////////////////////////
    LoggedDataPanelsManager nameView, telephoneView, emailView, departmentView, notesView;
    
    
    JButton btnSaveAll;
    JPanel pnlWarnings=new JPanel();
            
    private void initDisplay() {
        // must init the button so it will be enabled or disabled by the other fields
        if (isNewPi) {
            btnSaveAll=new JButton("Save New Pi");
            btnSaveAll.addActionListener(new ActionListener() {

                public void actionPerformed(ActionEvent e) {
                    createNewPiFromFields();
                }
            });
        }

        if (isNewPi) {
            lblId.setText("<Auto>");
        } else {
            lblId.setText(Integer.toString(pi.getId()));
        }

        ///////////////////////////////////////
        // adds all the internal data's views
        ///////////////////////////////////////
        
        LoggedData name=null, telephone=null, email=null, department=null, notes=null;
        if (!isNewPi) {
            name=pi.getLoggedDataName();
            telephone=pi.getLoggedDataTelephone();
            email=pi.getLoggedDataEmail();
            department=pi.getLoggedDataDepartment();
            notes=pi.getLoggedDataNotes();
        }
        nameView=createLoggedDataPanelManager(false, isNewPi, new LoggedDataPanelsText(), this, name, pnlFieldName);
        telephoneView=createLoggedDataPanelManager(false, isNewPi, new LoggedDataPanelsText(), this, telephone, pnlFieldPhone);
        emailView=createLoggedDataPanelManager(false, isNewPi, new LoggedDataPanelsText(), this, email, pnlFieldEmail);
        {
            LoggedDataPanelsListDepartment loggedDataPanelsListDepartment=new LoggedDataPanelsListDepartment();
            ChangeListener changeEventListener = new DepartmentchangeEventListener(loggedDataPanelsListDepartment);
            departmentView=createLoggedDataPanelManager(true, isNewPi, loggedDataPanelsListDepartment , this, department, pnlFieldDepartment, changeEventListener);
        }
        notesView=createLoggedDataPanelManager(false, isNewPi, new LoggedDataPanelsTextArea(), this, notes, pnlFieldNotes);


        
        JPanel pnlOptionalButtonsInner=new JPanel(new FlowLayout(FlowLayout.CENTER, 0, 0));
        pnlOptionalButtonsInner.setLayout(new GridLayout());
        
        boolean displayButtonsPanel=false;
        // if the grant is new, only allow to save the initial data
        // if not, allow to make transition of the grant request
        if (isNewPi) {
            JPanel pnlOptionalButtonsInner2=new JPanel(new BorderLayout(0, 0));
            pnlOptionalButtonsInner2.add(pnlWarnings, BorderLayout.NORTH);
            pnlOptionalButtonsInner2.add(btnSaveAll, BorderLayout.CENTER);
            pnlOptionalButtonsInner.add(pnlOptionalButtonsInner2);
            displayButtonsPanel=true;
        }
        
        if (!isNewPi) {
            JPanel pnlActionButtonsInner = new javax.swing.JPanel();
            JButton btnViewGrantRequests=new JButton("View My Grant Requests");
            btnViewGrantRequests.addActionListener(new btnViewGrantRequestsActionListener(this));
            pnlActionButtonsInner.add(btnViewGrantRequests);
            // allow interaction if saved 
            
            pnlActionButtons.add(wrapSection(pnlActionButtonsInner, "References"));
        }
        pnlActionButtons.setVisible(!isNewPi);
        
        pnlOptionalButtons.removeAll();
        // if no buttons, remove panel
        if (displayButtonsPanel) {
                pnlOptionalButtons.add(wrapSection(pnlOptionalButtonsInner, "Options"));
        }
        
        validateEntireForm();
        pack();
        setLocationRelativeTo(getParent());
        setVisible(true);
    }


    
    
    
    private void createNewPiFromFields() {
        try {

            Connection conn=Db.openDbConnection();
            PreparedStatement createGrantRequestStatement = Db.createPreparedStatement(conn, "INSERT INTO tblPis (NameRef, TelephoneRef, EmailRef, DepartmentRef, NotesRef) VALUES (?, ?, ?, ?, ?)");

            
            ////////////////////////////////////
            // Save all different data pieces
            ////////////////////////////////////
            
            createGrantRequestStatement.setInt(1, saveLoggedDataPanelsManagerData(nameView));
            createGrantRequestStatement.setInt(2, saveLoggedDataPanelsManagerData(telephoneView));
            createGrantRequestStatement.setInt(3, saveLoggedDataPanelsManagerData(emailView));
            createGrantRequestStatement.setInt(4, saveLoggedDataPanelsManagerData(departmentView));
            createGrantRequestStatement.setInt(5, saveLoggedDataPanelsManagerData(notesView));

            
            createGrantRequestStatement.executeUpdate();

            int newPiId = Db.getLastIdentity();
            createGrantRequestStatement.close();
            Db.closeDbConnection(conn);
            
            this.pi=Pi.getById(newPiId);
            
            //setVisible(false);
            
        } catch (SQLException ex) {
            Logger.getLogger(PiView.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        isNewPi=false;
        initDisplay();
                    
    }

    /////////////////////////
    // Validates the form
    /////////////////////////
    
    // each individual component is validates/invalidates seperately, using its designated Listener
    // the entire form is revalidated after any idnividual change
    
    private boolean isDepartmentValid=false;
    
    private void validateEntireForm() {
        setSaveEnabled(isDepartmentValid);
        pnlWarnings.removeAll();
        int warnings=0;
        if (!isDepartmentValid) {
            JLabel lblWarning=new JLabel("You must choose the department");
            lblWarning.setForeground(Color.RED);
            pnlWarnings.add(lblWarning);
            warnings++;
        }

        pnlWarnings.setLayout(new GridLayout(warnings, 1));
        pnlWarnings.revalidate();
    }
    
    private class DepartmentchangeEventListener implements ChangeListener {
        LoggedDataPanelsListDepartment loggedDataPanelsListDepartment;

        public DepartmentchangeEventListener(LoggedDataPanelsListDepartment loggedDataPanelsListDepartment) {
            this.loggedDataPanelsListDepartment = loggedDataPanelsListDepartment;
        }

        public void stateChanged(ChangeEvent e) {
            isDepartmentValid=((loggedDataPanelsListDepartment.isValid()) && (!loggedDataPanelsListDepartment.isEmpty()));
            validateEntireForm();
        }
    }

    private void setSaveEnabled(boolean enabled) {
        // will only be used when a global save button is availalbe
        if (btnSaveAll!=null) {
            btnSaveAll.setEnabled(enabled);
        }
    }

    
    
    
    public Pi getPi() {
        return(pi);
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel lblCaptionDepartment;
    private javax.swing.JLabel lblCaptionEmail;
    private javax.swing.JLabel lblCaptionId;
    private javax.swing.JLabel lblCaptionName;
    private javax.swing.JLabel lblCaptionNotes;
    private javax.swing.JLabel lblCaptionPhone;
    private javax.swing.JLabel lblId;
    private javax.swing.JPanel pnlActionButtons;
    private javax.swing.JPanel pnlDepartment;
    private javax.swing.JPanel pnlDepartment2;
    private javax.swing.JPanel pnlEmail;
    private javax.swing.JPanel pnlFieldDepartment;
    private javax.swing.JPanel pnlFieldEmail;
    private javax.swing.JPanel pnlFieldName;
    private javax.swing.JPanel pnlFieldNotes;
    private javax.swing.JPanel pnlFieldPhone;
    private javax.swing.JPanel pnlID;
    private javax.swing.JPanel pnlName;
    private javax.swing.JPanel pnlNotes;
    private javax.swing.JPanel pnlNotes2;
    private javax.swing.JPanel pnlOptionalButtons;
    private javax.swing.JPanel pnlPhone;
    // End of variables declaration//GEN-END:variables

    private class btnViewGrantRequestsActionListener implements ActionListener {

        PiView parent;

        public btnViewGrantRequestsActionListener(PiView parent) {
            this.parent = parent;
        }

        public void actionPerformed(java.awt.event.ActionEvent evt) {
            GrantRequestsList allGrantRequests = AllGrantRequests.getAllGrantRequests();
            GrantRequestsListFilters.filterByPiId(allGrantRequests, pi.getId());
            allGrantRequests.show(parent, "All Grant Requests for PI '" + parent.getPi().getCurrentName() + "'");
        }
    }

}
